<?php

class My_Form extends Zend_Form {

    const SUBMIT_ELEMENT_NAME = 'submit';

    protected $_title = '';
    protected $_mainCss = '';
    protected $_showLabels = true;
    protected $_addFormCancel = false;
    protected $_formCancelOptions = array();

    public function __construct($options = null) {
//        $this->addStylesheet('/css/form/base.css');   // loaded by layout
        $this->setMethod('post');
        $this->setAction($_SERVER['REQUEST_URI']);
        $this->setEnctype('multipart/form-data');

        $this->addPrefixPath('My_Form_Decorator', 'My/Form/Decorator/', 'decorator');
        $this->addPrefixPath('My_Form_Element', 'My/Form/Element/', 'element');

        $this->_formCancelOptions = array(
            'label' => $this->translate('XXX_MY_FORM_CANCEL_LABEL'),
        );

        parent::__construct($options);

        $this->addStylesheet('/css/form/base.css');
        $this->addStylesheet('/css/form/image-upload.css');
    }
    
    public function setAutosized(Zend_Form_Element $element) {
        $this->getView()->headScript()->appendFile('/libs/autosize/jquery.autosize-min.js');
        $this->getView()->headScript()->captureStart();
        ?>
        $(function(){ $('#<?= $element->getId() ?>').autosize(); });
        <?php
        $this->getView()->headScript()->captureEnd();
    }

    public function showLabels($showLabels = true) {
        $this->_showLabels = $showLabels;
    }

    public function setCSS($cssName) {
        $this->setAttrib('class', $cssName);
    }

    public function setCSSMain($cssName) {
        $this->_mainCss = $cssName;
    }

    public function addStylesheet($path) {
        $view = $this->getView();
        $view->headLink()->appendStylesheet($view->baseUrl() . $path);
    }

    public function loadDefaultDecorators() {
        $elems = $this->getElements();
        /* @var $e Zend_Form_Element */
        foreach ($elems as $e) {
            $options = array('tag' => 'td');
            $elementType = $this->getElementType($e);
            $class = 'type-' . $elementType . ' element-' . $e->getId();
            if ($e->hasErrors()) {
                $class .= ' error';
            }
            $decorators = array();
            if ($e instanceof My_Form_Element_ImageUpload) {
                $decorators[] = 'ImageUpload';
            } elseif ($e instanceof Zend_Form_Element_File) {
                $decorators[] = 'File';
            } else {
                $decorators[] = 'ViewHelper';
            }
            $e->setAttrib('class', $e->getAttrib('class'));

            if ($e instanceof Zend_Form_Element_Button || $e instanceof Zend_Form_Element_Submit) {
                $e->setAttrib('class', 'form_button button ' . $e->getAttrib('class'));
            }
            if ($e instanceof Zend_Form_Element_Submit) {
                $e->setAttrib('class', ' submit ' . $e->getAttrib('class'));
                if ($this->_addFormCancel) {
                    $decorators[] = array('FormCancel', $this->_formCancelOptions);
                }
            }
            $decorators[] = array('Description', array('tag' => 'div', 'class' => 'description'));
            $decorators[] = 'Errors';
            $options['class'] = $class;
            if ($e instanceof My_Form_Element_Description) {
                $decorators[] = array(array('data' => 'HtmlTag'), array('tag' => 'td', 'colspan' => 2, 'class' => 'data type-' . $elementType . ' element-' . $e->getId()));
            } else {
                $decorators[] = array(array('data' => 'HtmlTag'), array('tag' => 'td', 'class' => 'data type-' . $elementType . ' element-' . $e->getId()));
                if ($this->_showLabels) {
                    if ($e instanceof Zend_Form_Element_Button || $e instanceof Zend_Form_Element_Submit) {
                        $decorators[] = array('Label', array('tag' => 'td', 'class' => 'label-hidden', 'tagClass' => 'label-column'));
                    } else {
                        $decorators[] = array('Label', array('tag' => 'td', 'class' => 'label', 'tagClass' => 'label-column'));
                    }
                }
            }
            $decorators[] = array(array('row' => 'HtmlTag'), array('tag' => 'tr', 'class' => 'row row-type-' . $elementType . ' row-' . $e->getId()));
            $e->setDecorators($decorators);
        }
        $class = $this->getAttrib('class');
        if (!$class) {
            $class = '';
        }
        $formId = $this->getId();
        if(empty($formId)) {
            $formId = 'form_'.uniqid();
            $this->setAttrib('id', $formId);
        }
        $formId = $this->getId();
        $this->setAttrib('class', 'form ' . $this->_mainCss . ' ' . $class);
        $formTitleCss = empty($this->_mainCss) ? '' : $this->_mainCss . '-title';
        $this->setDecorators(array(
            array('FormErrors', array(
                    'ignoreSubForms' => false,
                    'showCustomFormErrors' => true,
                    'onlyCustomFormErrors' => true,
                    'markupElementLabelEnd' => '</b>',
                    'markupElementLabelStart' => '<b>',
                    'markupListItemEnd' => '',
                    'markupListItemStart' => '',
                    'markupListStart' => '<div class="form-errors">',
                    'markupListEnd' => '</div>',
                )
            ),
            'FormElements',
            array('HtmlTag', array('tag' => 'table', 'class' => 'form_elements')),
            'form',
            array('FormTitle', array('class' => $formTitleCss)),
        ));
    }

    public function render(Zend_View_Interface $view = null) {
        $elements = $this->getElements();
        /* @var $e Zend_Form_Element */
        foreach ($elements as $e) {
            if ($e->hasErrors()) {
                $decorator = $e->getDecorator('row');
                $class = $decorator->getOption('class');
                $class .= ' errors';
                $decorator->setOption('class', $class);
            }
        }
        return parent::render($view);
    }

    protected function getElementType($e) {
        $t = $e->getType();
        $w = explode('_', $t);
        return strtolower($w[count($w) - 1]);
    }

    /**
     *
     * @return Zend_Form_Element_Submit 
     */
    protected function addSubmitElement() {
        $btn = new Zend_Form_Element_Submit(self::SUBMIT_ELEMENT_NAME);
        $btn->setLabel(_('XXX_FORM_GENERIC_SUBMIT_BTN'));
        $btn->setAttrib('class', 'btn btn-primary btn-large');
        $this->addElement($btn);
        return $btn;
    }

    /**
     *
     * @return Zend_Form_Element_Submit 
     */
    protected function getSubmitElement() {
        return $this->getElement(self::SUBMIT_ELEMENT_NAME);
    }

    protected function setSubmitLabel($label) {
        return $this->getSubmitElement()->setLabel($label);
    }

    public function getTitle() {
        return $this->_title;
    }

    public function setTitle($title) {
        $this->_title = $title;
    }

    public function _($key, array $data = null) {
        $msg = $this->getTranslator()->_($key);
        if ($data != null && !empty($data)) {
            $tmpkeys = array_keys($data);
            $vals = array_values($data);
            $keys = array();
            foreach ($tmpkeys as $tmpkey) {
                $keys[] = '%' . $tmpkey . '%';
            }
            $msg = str_replace($keys, $vals, $msg);
        }
        return $msg;
    }

    public function translate($key, array $data = null) {
        return $this->_($key, $data);
    }

}
